package triannon.client.util;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import triannon.client.interfaces.IXML;

public class XMLIO {

	public static void writeXML(IXML ixml, String filename) {
		XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

		OutputStream out = null;

		try {
			out = new FileOutputStream(filename);
			xmlOutputter.output(ixml.toXML(), out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (Exception e) {
			}
		}
	}

	public static Element readXML(InputStream is) {
		SAXBuilder builder = new SAXBuilder();

		try {
			return builder.build(is).getRootElement();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception e) {
			}
		}

		return null;
	}

	public static Element readXML(URL url) {
		SAXBuilder builder = new SAXBuilder();

		InputStream is = null;

		try {
			is = url.openStream();
			return builder.build(is).getRootElement();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Exception e) {
			}
		}

		return null;
	}

	public static Element readXML(String filename) {
		SAXBuilder builder = new SAXBuilder();

		try {
			return builder.build(filename).getRootElement();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
